package com.sdry.product.waitingarea.service;
import	java.util.HashSet;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sdry.basic.entity.Material;
import com.sdry.common.BaseAPIMessageTypeEnum;
import com.sdry.exception.BizException;
import com.sdry.good.goodChain.entity.GoodChain;
import com.sdry.good.goodChain.service.GoodChainService;
import com.sdry.good.goodWarehouse.entity.GoodContainerStare;
import com.sdry.good.goodWarehouse.entity.GoodSortFrame;
import com.sdry.good.goodWarehouse.mapper.GoodSortFrameMapper;
import com.sdry.good.goodWarehouse.service.GoodContainerStareService;
import com.sdry.good.goodWarehouse.service.GoodSortFrameService;
import com.sdry.product.prod.entity.ResultAppList;
import com.sdry.product.waitingarea.entity.ChoicePlan;
import com.sdry.product.waitingarea.entity.ChoicePlanDetail;
import com.sdry.product.waitingarea.entity.StayContainerStare;
import com.sdry.product.waitingarea.mapper.ChoicePlanDetailMapper;
import com.sdry.product.waitingarea.mapper.ChoicePlanMapper;
import com.sdry.product.waitingarea.mapper.StayContainerStareMapper;
import com.sdry.untils.CustomUtil;
import com.sdry.untils.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 备货计划
 * @Author chenBin
 * @Date 2020-03-27 14:48
 * @Version 1.0
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class StayContainerStareServiceImpl implements StayContainerStareService{

    @Resource
    private StayContainerStareMapper stayContainerStareMapper;

    @Resource
    private GoodChainService goodChainService;

    @Resource
    private GoodSortFrameService goodSortFrameService;

    @Resource
    private GoodContainerStareService  goodContainerStareService;
    @Resource
    GoodSortFrameMapper goodSortFrameMapper;

    @Resource
    private ChoicePlanDetailMapper choicePlanDetailMapper;

    @Resource
    private ChoicePlanMapper choicePlanMapper;

    /**
     * 成品库或者成品链库存
     * @param type 类型 1-代表成品链，2-代表成品库
     * @return List<ResultAppList<Material>>
     */
    @Override
    public List<ResultAppList<Material>> queryProductContainer(String type) {
        List<Material> materialList = new ArrayList<>();
        //专门用来存储工位或者容器
        HashSet<String> hashSet = new HashSet<> ();
        //1-代表成品链
        if ("1".equals(type)){
           materialList = stayContainerStareMapper.queryProductContainer1();
        }if ("2".equals(type)){
            materialList = stayContainerStareMapper.queryProductContainer2();
        }
        return CustomUtil.QueryResultChange2(materialList);
    }

    /**
     * 验证自定义编号是否存在
     * @param number 编号
     * @return boolean
     */
    @Override
    public boolean verificationNumber(String number) {
        QueryWrapper<StayContainerStare> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("remark1","0").eq("code",number);
        Integer integer = stayContainerStareMapper.selectCount(queryWrapper);
        if (integer <= 0){
            return true;
        }
        return false;
    }

    @Override
    public void addStayContainerStare(String json, String userId, String code) {
        Gson gson = new Gson();
        ResultAppList<Material> materialResultAppList = gson.fromJson(json, ResultAppList.class);
        String jsonObject = String.valueOf(materialResultAppList.getList());
        List<Material> materialList= gson.fromJson(jsonObject, new TypeToken<List<Material>>() {}.getType());
        for (Material material : materialList) {
            /**
             * 1.判断是来自成品链还是成品库物料
             * “1”代表的是成品链
             * “2”d代表的是成品库
             */
            if (material.getRemark04().equals("1")){
                //1.减去成品链
                productLibrary(material,materialResultAppList,code,userId);
            }else if (material.getRemark04().equals("2")) {
                finishedProductLibrary(material,materialResultAppList,code,userId);
            }

        }
    }

    /**
     * 成品库
     * 1.查询某个物料的所有库存，即为总的库存
     * 2.需求数量与库存数量对比
     * a.需求数量等于库存数量，全部出库，减库存
     * b.需求数量大于库存数量
     * c.需求数量小于库存数量
     * @param material 物料
     * @param materialResultAppList 编号
     * @param code 条码
     * @param userId 用户ID
     */
    private void finishedProductLibrary(Material material, ResultAppList<Material> materialResultAppList, String code, String userId) {
        //2.成品库库存情况
        GoodSortFrame goodSortFrameTJ = new GoodSortFrame();
        GoodContainerStare goodContainerStare = new GoodContainerStare();
        //条件1
        goodContainerStare.setCode(materialResultAppList.getPsnumber());
        goodSortFrameTJ.setGoodContainerStare(goodContainerStare);
        goodSortFrameTJ.setDelFlag("0");
        GoodContainerStare goodContainerStareTJ = new GoodContainerStare();
        //条件2
        goodContainerStareTJ.setMaId(material.getMaId());
        goodSortFrameTJ.setGoodContainerStare(goodContainerStareTJ);
        List<GoodSortFrame> goodSortFrameList = goodSortFrameMapper.queryAllByMution(goodSortFrameTJ);
        //库存总数量
        Long gcNum = 0L;
        for (GoodSortFrame goodSortFrame : goodSortFrameList) {
            int gcNum1 = goodSortFrame.getGoodContainerStare().getGcNum();
            gcNum += gcNum1;
        }
        //需求数量
        Long demandQuantity = material.getQuantity();
        if (demandQuantity.equals(gcNum)){
            //相等
            for (GoodSortFrame goodSortFrame : goodSortFrameList) {
                //主键
                Long gcId = goodSortFrame.getGoodContainerStare().getGcId();
                Integer effect = stayContainerStareMapper.deleteGoodContainerStare(gcId);
                if (effect <= 0){
                    throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                }
            }
        }else if (demandQuantity.longValue() < gcNum.longValue()){

            for (GoodSortFrame goodSortFrame : goodSortFrameList) {
                Long materialGcNum = Long.valueOf(goodSortFrame.getGoodContainerStare().getGcNum());
                //主键
                Long gcId = goodSortFrame.getGoodContainerStare().getGcId();
                if (demandQuantity.equals(materialGcNum)){
                    Integer effect = stayContainerStareMapper.deleteGoodContainerStare(gcId);
                    if (effect <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                }else if (demandQuantity < materialGcNum){
                    Long quantity = materialGcNum - demandQuantity;
                    Integer effect = stayContainerStareMapper.updateGoodContainerStare(gcId,quantity);
                    if (effect <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                }else if (demandQuantity > materialGcNum){
                    Long quantity = demandQuantity - materialGcNum;
                    Integer effect = stayContainerStareMapper.updateGoodContainerStare(gcId,quantity);
                    if (effect <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                    demandQuantity = quantity;
                }
            }

        }else if (demandQuantity > gcNum) {
            //库存小
            throw  new BizException(BaseAPIMessageTypeEnum.A096.getName());
        }
        add(materialResultAppList,userId,material,code);
    }

    public void add(ResultAppList<Material> materialResultAppList,String userId,Material material,String code) {
        //3.绑定表里添加
        StayContainerStare stayContainerStare = new StayContainerStare();
        //条码或者编号
        stayContainerStare.setCode(code);
        //物料
        stayContainerStare.setMaId(material.getMaId());
        //数量
        stayContainerStare.setCsrnum(material.getQuantity());
        //操作人员
        stayContainerStare.setCreate_by(userId);
        int insert = stayContainerStareMapper.insert(stayContainerStare);
        if (insert <= 0){
            throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
        }
    }

    @Override
    public List<StayContainerStare> queryStayContainerStarePage(StayContainerStare stayContainerStare) {
        return stayContainerStareMapper.queryStayContainerStarePage(stayContainerStare);
    }

    @Override
    public Long queryStayContainerStareTotal(StayContainerStare stayContainerStare) {
        return stayContainerStareMapper.queryStayContainerStareTotal(stayContainerStare);
    }

    @Override
    public boolean addChoicePlan(String quantitys, String maIds, String remark1, String plNumber) {
        ChoicePlan choicePlan = new ChoicePlan();
        //操作人员
        choicePlan.setCreateBy(UserContext.getSessionUserIdByServiceImpl().toString());
        //编号
        choicePlan.setPlNumber(plNumber);
        //时间
        choicePlan.setRemark1(remark1);
        choicePlanMapper.insert(choicePlan);
        String[] strIds = maIds.split(",");
        String[] quantity = quantitys.split(",");
        for (int i = 0; i < strIds.length; i++) {
            ChoicePlanDetail choicePlanDetail = new ChoicePlanDetail();
            //物料ID
            choicePlanDetail.setMaterielId(Long.parseLong(strIds[i]));
            //数量
            choicePlanDetail.setQuantity(Long.parseLong(quantity[i]));
            //单子ID
            choicePlanDetail.setPlId(choicePlan.getPlId());
            choicePlanDetailMapper.insert(choicePlanDetail);
        }
        return true;
    }

    @Override
    public List<ChoicePlan> queryAddChoicePlanPage(StayContainerStare stayContainerStare) {
        return choicePlanMapper.queryAddChoicePlanPage(stayContainerStare);
    }

    @Override
    public Long queryAddChoicePlanTotal(StayContainerStare stayContainerStare) {
        return choicePlanMapper.queryAddChoicePlanTotal(stayContainerStare);
    }

    @Override
    public Integer deleteStayContainerStare(Long plDeId) {
        ChoicePlanDetail entity = new ChoicePlanDetail();
        entity.setPlDeId(plDeId);
        entity.setDelFlag("1");
        return choicePlanDetailMapper.updateById(entity);
    }

    /**
     * 成品链
     * 1.查询某个物料成品链总库存
     * 2.需求数量与成品链总数量进行对比
     * a.需求数量等于成品链总库存，全部出库，减去成品库存
     * b.需求数量大于成品链总库存，提示需求数量大于成品链条数量
     * c.需求数量小于成品链总库存，出库需求数量，减去库存需求数量
     * @param material 物料
     * @param materialResultAppList
     * @param code
     * @param userId
     */
    public void productLibrary(Material material, ResultAppList<Material> materialResultAppList, String code, String userId){
        //(1).成品链
        List<GoodChain> goodChainList = stayContainerStareMapper.queryGoodChain(material.getPsId(),material.getMaId());
        if (goodChainList.size() == 0 || goodChainList == null){
            throw new BizException(BaseAPIMessageTypeEnum.A096.getName());
        }
        //某个容器某个物料总和,即为库存数量
        Long quantity = 0L;
        for (GoodChain goodChain : goodChainList) {
            Long maNum = goodChain.getMaNum();
            if (maNum == null) {
                continue;
            }
            quantity += maNum;
        }
        //需求数量
        Long demandQuantity = material.getQuantity();
        if (demandQuantity.equals(quantity)) {
            //相等的话，直接删除一条记录
            for (GoodChain goodChain : goodChainList) {
                Long gcId = goodChain.getGcId();
                Integer effect = stayContainerStareMapper.deleteGoodChain(gcId);
                if (effect <= 0){
                    throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                }
            }

        }else if (demandQuantity < quantity){
            for (GoodChain goodChain : goodChainList) {
                Long maNum = goodChain.getMaNum();
                if (maNum.equals(demandQuantity)){
                    Integer effect = stayContainerStareMapper.deleteGoodChain(goodChain.getCPsId());
                    if (effect <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                }else if (maNum < demandQuantity){
                    Integer effect = stayContainerStareMapper.updateGoodChain(goodChain.getGcId(),maNum);
                    if (effect <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                    demandQuantity = demandQuantity -maNum;
                }else if (maNum > demandQuantity) {
                    Long num = maNum - demandQuantity;
                    Integer effect = stayContainerStareMapper.updateGoodChain(goodChain.getGcId(),num);
                    if (effect <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                }
            }
        }else if (demandQuantity > quantity) {
            //出库的数量大于库存数量，不可能报错
            throw new BizException(BaseAPIMessageTypeEnum.A096.getName());
        }

        add(materialResultAppList,userId,material,code);
    }
}
